package com.wwj.study.rmi.rpc.server;

import com.wwj.study.rmi.rpc.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

public class ProcessHandler implements Runnable {

    private Socket socket;
    private Object o;

    public ProcessHandler(Socket socket, Object o) {
        this.socket = socket;
        this.o = o;
    }

    //处理请求
    public void run() {


        ObjectInputStream objectInputStream=null;
        ObjectOutputStream objectOutputStream=null;
        try {
            Thread.sleep(1000L);
            System.out.println("线程休眠1000"+Thread.currentThread().getName());

            //读对象
            objectInputStream=new ObjectInputStream(socket.getInputStream());
            //获取客户端传过来的对象
            Object result=objectInputStream.readObject();
            RpcRequest rpcRequest= (RpcRequest)result;
            //执行方法，返回结果
            Object outputObject= invoke(rpcRequest);
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            //结果写回客户端
            objectOutputStream.writeObject(outputObject);
            objectOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(objectInputStream!=null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(objectOutputStream!=null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Object invoke(RpcRequest rpcRequest) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //反射获取参数的所有类型
        Object [] args=rpcRequest.getParams();
        Class<?>[] argsClass=new Class[args.length];

        for (int i=0;i<args.length;i++) {
            Object o= args[i];
            argsClass[i]=o.getClass();
        }

        Method method=o.getClass().getMethod(rpcRequest.getMethodName(),argsClass);
        return method.invoke(o,args);
    }
}
